package edu.simplemqom.protocol;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class SMQOMPackage {
	
	private byte[] data;
	
	private byte commandId;
	
	private int sessionId;
	
	public SMQOMPackage() {
		data = null;
		commandId = 0x00;
		sessionId = -1;
	}
	
	public SMQOMPackage(byte commandId, int sessionId, byte[] content) {
		this.commandId = commandId;
		this.sessionId = sessionId;
		if (content != null) {
			this.data = new byte[content.length];
			System.arraycopy(content, 0, this.data, 0, this.data.length);
		}
		
		this.data = content;
	}
	
	public int getDataSize() {
		if (data == null) {
			return 0;
		}
		
		return data.length;
	}
	
	public int getSize() {
		return 11+getDataSize();
	}
	
	public byte getCommandId() {
		return this.commandId;
	}
	
	public int getSessionId() {
		return this.sessionId;
	}
	
	public void setCommandId(byte cmdId) {
		this.commandId = cmdId;
	}
	
	public void setData(byte[] data) {
		this.data = new byte[data.length];
		
		System.arraycopy(data, 0, this.data, 0, this.data.length);
	}
	
	public byte[] getBytes() {
		int bufferSize = 11+getDataSize();
		ByteBuffer temp = ByteBuffer.allocate(bufferSize);
		temp.order(ByteOrder.BIG_ENDIAN);
		
		temp.put(SMQOMCommandId.SMQOM_MAGIC);
		temp.putInt(sessionId);
		temp.putInt(getDataSize());
		temp.put(commandId);
		
		if (data != null)
			temp.put(data);
		temp.put(SMQOMCommandId.SMQOM_MAGIC);
		
		return temp.array();
	}
	
	public byte[] getDataBytes() {
		if (data == null) {
			return null;
		}
		
		byte[] res = new byte[data.length];
		
		System.arraycopy(data, 0, res, 0, res.length);
		return res;
	}

}
